import * as API from '@/api/admin/wx-member-tags.js'
const WxTags = {
  state: {
    tags: [],
    hasLoading: false
  },
  getters: {
    isTagsLoading: state => {
      return state.hasLoading
    }
  },
  mutations: {
    CREATE_TAG (state, tag) {
      tag.count = 0
      state.tags.push(tag)
    },
    UPDATE_TAG (state, { id, name }) {
      state.tags = state.tags.map(e => {
        if (e.id === id) {
          e.name = name
          return e
        } else {
          return e
        }
      })
    },
    DELETE_TAG (state, id) {
      const i = state.tags.findIndex(e => e.id === id)
      state.tags.splice(i, 1)
    },
    SET_TAGS (state, tags) {
      state.tags = tags
      state.hasLoading = true
    }
  },
  actions: {
    getTags ({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.hasLoading) {
          resolve(state.tags)
        } else {
          API.getAllTags().then(res => {
            commit('SET_TAGS', res.data.tags)
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        }
      })
    },
    updateTag ({ commit }, tag) {
      return new Promise((resolve, reject) => {
        API.updateTag(tag.id, tag.name).then(res => {
          commit('UPDATE_TAG', { id: tag.id, name: tag.name })
          resolve('修改成功！')
        })
      })
    },
    createTag ({ commit }, name) {
      return new Promise((resolve, reject) => {
        API.createTag(name).then(res => {
          commit('CREATE_TAG', res.data.tag)
          resolve('创建成功！')
        })
      })
    },
    deleteTag ({ commit }, id) {
      return new Promise((resolve, reject) => {
        API.deleteTag(id).then(res => {
          commit('DELETE_TAG', id)
          resolve('删除成功！')
        })
      })
    }
  }
}
export default WxTags
